<?php


namespace app\home\controller\file;

use app\common\controller\BaseController;
use app\common\validate\file\FileValidate;
use app\common\service\file\FileService;
use app\common\service\file\GroupService;
use app\common\service\file\TagService;
use app\common\service\file\SettingService;
use hg\apidoc\annotation as Apidoc;
use QCloud\COSSTS\Sts;

/**
 * @Apidoc\Title("文件")
 * @Apidoc\Group("upload")
 * @Apidoc\Sort("380")
 */
class Upload extends BaseController
{
    /**
     * @Apidoc\Title("上传文件")
     * @Apidoc\Method("POST")
     * @Apidoc\ParamType("formdata")
     * @Apidoc\Param("group_id", type="string", require=false, desc="分组id或标识")
     * @Apidoc\Param("tag_ids", type="string", require=false, desc="标签id或标识，多个逗号隔开")
     * @Apidoc\Param(ref="app\common\model\file\FileModel", field="file_type,file_name")
     * @Apidoc\Param(ref="fileParam")
     * @Apidoc\Returned(ref="fileReturn")
     */
    public function file()
    {
        $setting = SettingService::info();
        if (!$setting['is_upload_api']) {
            return error('文件上传未开启，无法上传文件！');
        }

        $param = $this->params([
            'group_id'    => 0,
            'tag_ids'     => '',
            'file_type/s' => 'image',
            'file_name/s' => '',
        ]);
        $param['file']     = $this->request->file('file');
        $param['is_front'] = 1;

        validate(FileValidate::class)->scene('add')->check($param);

        if ($param['group_id']) {
            $group = GroupService::info($param['group_id'], false);
            $param['group_id'] = $group['group_id'] ?? 0;
        }
        $tag_ids = [];
        if ($param['tag_ids']) {
            if (is_string($param['tag_ids'])) {
                $param['tag_ids'] = explode(',', $param['tag_ids']);
            }
            foreach ($param['tag_ids'] as $tag_id) {
                $tag = tagService::info($tag_id, false);
                if ($tag) {
                    $tag_ids[] = $tag['tag_id'] ?? 0;
                }
            }
        }
        $param['tag_ids'] = $tag_ids;

        $data = FileService::add($param);

        return success($data, '上传成功');
    }

    /**
     * @Apidoc\Title("获取临时密钥")
     * @Apidoc\Method("GET")
     */
    public function getTempSec()
    {
        $sts = new Sts();
        $config = array(
            'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
            'domain' => 'sts.tencentcloudapi.com', // 域名，非必须，默认为 sts.tencentcloudapi.com
            'proxy' => '',
            'secretId' => "AKIDINN7sOhgtseAPPQIQIlz9ERYaP3CFKEw", // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'secretKey' => "XoqaBVjiS0kEZfVHoCYeU4VyFE0eEY6O", // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'bucket' => 'ai-dev-1305433883', // 换成你的 bucket
            'region' => 'ap-guangzhou', // 换成 bucket 所在园区
            'durationSeconds' => 1800, // 密钥有效期
            'allowPrefix' => array('*'), // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions' => array (
                // 简单上传
                'name/cos:PutObject',
                'name/cos:GetObject',
                'name/cos:HeadBucket',
                'name/cos:HeadObject',
                'name/cos:OptionsObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ),
            // 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
//            "condition" => array(
//                "ip_equal" => array(
//                    "qcs:ip" => array(
//                        "*",
//                    )
//                )
//            )
        );

        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        $tempKeys["bucket"] = $config["bucket"];
        $tempKeys["region"] = $config["region"];
        return success($tempKeys, '获取成功');

    }
}
